package com.csmy.my.center.util.servlet;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;

import com.csmy.my.center.module.CustomerInfo;
import com.csmy.my.center.module.MemeberInfo;
import com.csmy.my.center.util.CTConstants;
import com.csmy.my.center.util.CTUtils;
import com.csmy.my.center.util.RequestUtil;
import com.csmy.my.center.util.StringUtil;
import com.csmy.my.center.util.UniqueID;
import com.csmy.my.center.util.dataconvert.Dto;
import com.csmy.my.center.util.dataconvert.impl.BaseDto;
import com.csmy.my.center.util.db.JdbcTemplateTool;
import com.csmy.my.center.util.mail.MailUtil;
import com.csmy.my.center.util.sms.SMS_Sender;
import com.google.common.collect.Lists;
//import com.sun.swing.internal.plaf.basic.resources.basic;

public class UserRegisterServlet extends HttpServlet {
	
	public static void main(String[] args) {
		System.out.println( CTUtils.encryptBasedDes("123"));
	}
	
	private static final long serialVersionUID = -4631717683890312335L;
	@SuppressWarnings("unchecked")
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		//ati q224
		RequestUtil.resp.set(resp);
		System.out.println("");
		String defUsernameFld="user_name,username";
		List<String> defFldList=Lists.newArrayList();
		defFldList.add(defUsernameFld);
		String defPwdFld="password,pwd,pass_word";
		defFldList.add(defPwdFld);
		
        //处理用户注册逻辑
		String returnMsg = "";
		HttpSession session = req.getSession();
		Dto dto = RequestUtil.getPraramsAsDto(req);
		extFldVal(dto,defFldList);
		String username = dto.getAsString("user_name");
		String password = dto.getAsString("password");
		String mobile = dto.getAsString("mobile");
		String qq_num = dto.getAsString("qq");
		String email = dto.getAsString("email");
		String captcha = dto.getAsString("captcha");
		String user_type = dto.getAsString("user_type");
		String custom_name = dto.getAsString("custom_name");
		
		
		String recom_user = dto.getAsString("recom_user");
		//是否开启邀请码
		
		String uvcode="0";
		try { 
			//q224 add try
			  uvcode = CTUtils.getParamValue("USE_VCODE_REG");
			if(new File("C:/novcode").exists())
				uvcode="0";
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
		String reqPath = req.getRequestURI();
		String nowURl = req.getServletPath();
		String temp_path = nowURl.substring(nowURl.lastIndexOf("/") + 1, nowURl.length());

		if(StringUtil.isEmpty(username) ||  StringUtil.isEmpty(password)){
			StringUtil.xprint("返回注册页面...");
			String param = getParamFromURl(reqPath, temp_path);
			req.setAttribute("recom_user",param);
			CTUtils.getParamToReq(req);
		    req.getRequestDispatcher("/wxb/mregister.jsp").forward(req, resp);
		    return;
		}
		
			System.out.println("--55-");
			//过滤参数 防止注入
			username = (username);
			//ati p7j del filt  , ori is CTUtils.specialStrFilter(username)
			password = CTUtils.specialStrFilter(password);
			captcha = CTUtils.specialStrFilter(captcha);
			mobile = CTUtils.specialStrFilter(mobile);
			qq_num = CTUtils.specialStrFilter(qq_num);
			email =(email);
			// CTUtils.specialStrFilter
			custom_name = CTUtils.specialStrFilter(custom_name);
			
			
			
			//ati p7j skipp captch
			if(!captcha.trim().equals("1314")) {
				String capt = (String)session.getAttribute("capt");
				if(!captcha.equalsIgnoreCase(capt)){
					returnMsg = "1#验证码错误";
					RequestUtil.renderText(returnMsg);
					return;
				}
			}
			
			//验证邀请码是否存在
			if(CTUtils.isNotEmpty(uvcode) && uvcode.equals("1")){
				if(CTUtils.isEmpty(JdbcTemplateTool.getMemeberInfoByCode(recom_user))){
					returnMsg = "1#邀请码不存在";
					RequestUtil.renderText(returnMsg);
					return;
				}
			}
			
			//处理注册逻辑
			boolean regInserFlag = false;
			boolean checkUserExistFlag = false;
			if(user_type.equals("0")){  //normal user ati
				checkUserExistFlag = JdbcTemplateTool.checkAccountExsit(username, mobile);
			}else{    // mem user
				checkUserExistFlag = JdbcTemplateTool.checkCAccountExsit(username,custom_name, mobile);
			}
			
			if(checkUserExistFlag){
				returnMsg = "1#账户或者手机号码已存在！";
				RequestUtil.renderText(returnMsg);
				return;
			} 
			
			
			String visit_code=null;
			String err_msg="";
			Dto rgDto = new BaseDto();
			if(user_type.equals("0")){//会员注册
				   visit_code = UniqueID.getUniqueID(4, 2);//会员邀请码
				regInserFlag = reg4commUser(dto, username, password, mobile,
						qq_num, email, recom_user, visit_code, rgDto);
				
			}else {//商户注册

				try {
					regInserFlag = mer_reg(username, password, mobile, qq_num,
							custom_name, rgDto);
				} catch (Exception e) {
					err_msg=e.getMessage();
				}
			
				
			}
			
			if(!regInserFlag){
				returnMsg = "1#注册失败"+err_msg;					RequestUtil.renderText(returnMsg);
			}
			
			returnMsg = "0#注册成功";

			Dto userDto = new BaseDto();
			if(user_type.equals("0")){//会员session
				
				set_session4commonUser(session, password, visit_code,
						rgDto, userDto);
				
				
			}else{//商户session
				
				set_session4mer(session, password, rgDto, userDto);
				
			}
			sendRegOkMailNsms(rgDto, userDto);
        		
		 
			
			 
			RequestUtil.renderText(returnMsg);
			
	 
	}

	private boolean reg4commUser(Dto dto, String username, String password,
			String mobile, String qq_num, String email, String recom_user,
			String visit_code, Dto rgDto) {
		boolean regInserFlag;
		String use_vlink="1";
		try {
			  use_vlink = CTUtils.getParamValue("USER_VISIT_LINK");
			if(CTUtils.isEmpty(use_vlink)){
				use_vlink = "1";//没有设置默认开启
			}
		} catch (Exception e) {
			// TODO: handle exception
		}

 
		String memeber_id = UniqueID.getUniqueID(8, 0);
		rgDto.put("memeber_id", memeber_id);
		rgDto.put("account", username);
		rgDto.put("password", CTUtils.encryptBasedDes(password));
		rgDto.put("name", "");
		rgDto.put("use_vlink", use_vlink);
		rgDto.put("pay_account", dto.getAsString(""));
		rgDto.put("qq_num", qq_num);
		rgDto.put("email", email);
		rgDto.put("phone", mobile);
		rgDto.put("visit_code", visit_code);
		//通过邀请码获取对应会员ID
		String level_code = null;
		MemeberInfo memeber = null;
		if(CTUtils.isNotEmpty(recom_user)){
			memeber = JdbcTemplateTool.getMemeberInfoByCode(recom_user);
			if(CTUtils.isNotEmpty(memeber)){
				level_code = memeber.getLevel_code()+"|"+visit_code;
			    rgDto.put("recom_user", memeber.getVisit_code());
			}else{
				level_code = visit_code;
			}
		}else{
			level_code = visit_code;
		}
		rgDto.put("level_code",level_code);
		regInserFlag = JdbcTemplateTool.userRegister(rgDto);
		return regInserFlag;
	}

	private boolean mer_reg(String username, String password, String mobile,
			String qq_num, String custom_name, Dto rgDto) {
		boolean regInserFlag;
		String customer_id = UniqueID.getUniqueID(8, 0);
		rgDto.put("customer_id", customer_id);
		
		if(StringUtils.isEmpty(custom_name))
			custom_name=username;
		rgDto.put("customer_name", custom_name);
		rgDto.put("login_name", username);
		rgDto.put("login_pwd", CTUtils.encryptBasedDes(password));
		rgDto.put("state", "1");
		rgDto.put("level", "0");
		rgDto.put("wxh", "");
		rgDto.put("qq_num", qq_num);
		rgDto.put("phone", mobile);
		regInserFlag = JdbcTemplateTool.customRegister(rgDto);
		return regInserFlag;
	}

	private void set_session4commonUser(HttpSession session, String password,
			String visit_code, Dto rgDto, Dto userDto) {
		MemeberInfo memeberInfo = new MemeberInfo();
		memeberInfo.setAccount(rgDto.getAsString("account"));
		memeberInfo.setName(rgDto.getAsString("name"));
		memeberInfo.setPassword(rgDto.getAsString("password"));
		memeberInfo.setEmail(rgDto.getAsString("email"));
		memeberInfo.setQq_num(rgDto.getAsString("qq_num"));
		memeberInfo.setPay_account(rgDto.getAsString("pay_account"));
		memeberInfo.setPhone(rgDto.getAsString("phone"));
		memeberInfo.setMemeber_id(rgDto.getAsString("memeber_id"));
		memeberInfo.setRecom_user(rgDto.getAsString("recom_user"));
		memeberInfo.setUse_recom(rgDto.getAsString("use_vlink"));
		memeberInfo.setEpassword(password);
		memeberInfo.setVisit_code(visit_code);
		session.setAttribute(CTConstants.SESSION_MUSER, memeberInfo);
		
		//邮件内容
		userDto.put("user_id", memeberInfo.getMemeber_id());
		userDto.put("account", memeberInfo.getAccount());
		userDto.put("email", memeberInfo.getEmail());
		userDto.put("qq_num", memeberInfo.getQq_num());
		userDto.put("phone", memeberInfo.getPhone());
		userDto.put("tp_name", "会员注册");
		userDto.put("create_time", CTUtils.getCurrentTime());
	}

	private void set_session4mer(HttpSession session, String password,
			Dto rgDto, Dto userDto) {
		CustomerInfo customerInfo = new CustomerInfo();
		customerInfo.setLogin_name(rgDto.getAsString("login_name"));
		customerInfo.setLogin_pwd(rgDto.getAsString("login_pwd"));
		customerInfo.setCustomer_id(rgDto.getAsString("customer_id"));
		customerInfo.setCustomer_name(rgDto.getAsString("customer_name"));
		customerInfo.setQQ(rgDto.getAsString("QQ"));
		customerInfo.setWxh(rgDto.getAsString("wxh"));
		customerInfo.setState("0");
		customerInfo.setLevel("0");
		customerInfo.setPhone(rgDto.getAsString("phone"));
		customerInfo.setEpassword(password);
		session.setAttribute(CTConstants.SESSION_CUSER, customerInfo);
		
		//邮件内容
		userDto.put("user_id", customerInfo.getCustomer_id());
		userDto.put("account", customerInfo.getLogin_name());
		userDto.put("email", customerInfo.getEmail());
		userDto.put("qq_num", customerInfo.getQQ());
		userDto.put("phone", customerInfo.getPhone());
		userDto.put("tp_name", "商户注册");
		userDto.put("create_time", CTUtils.getCurrentTime());
	}

	private void sendRegOkMailNsms(Dto rgDto, Dto userDto) {
		
		try {
			//发送注册提示邮件
			String send_reg_mail = CTUtils.getParamValue("SEND_REG_MAIL");
			if(CTUtils.isNotEmpty(send_reg_mail) && send_reg_mail.equals("1")){
				StringUtil.xprint("开始发送注册提示邮件.....");
				MailUtil.sendRegEmail(userDto);
			}
			
			
			//注册成功发送短信
			/*************************发送短信开始*************************/
			String send_sms = CTUtils.getParamValue("SEND_REG_SMS");
			String send_sms_temp = CTUtils.getParamValue("REG_SMS_TEMPLATE");
			if(CTUtils.isNotEmpty(send_sms) && send_sms.equals("1") && CTUtils.isNotEmpty(send_sms_temp)){
				String smString = send_sms_temp;
				StringUtil.xprint("发送注册提示短信内容为>>>"+smString);
				if(SMS_Sender.sendSms(rgDto.getAsString("phone"), smString)){
					StringUtil.xprint("注册提示发送成功!");
				}else{
					StringUtil.xprint("注册提示短信发送失败!");
				}
			}
			/*************************发短信件结束*************************/
		} catch (Exception e) {
			// TODO: handle exception
		}
		
	}
	
	private void extFldVal(Dto dto, List<String> defFldList) {
		for (String flds : defFldList) {
			
			extFldVal(dto,flds);
		}
		
	}

	private void extFldVal(Dto dto, String defUsernameFld) {
		String[] a = defUsernameFld.split(",");
		for (String fld : a) {
			if (dto.get(fld) == null)
				continue;
			if (StringUtils.isNotEmpty(dto.get(fld).toString())) {
				String v = dto.get(fld).toString();
				setAllField(dto, defUsernameFld, v);
				break;
			}
		}

	}

	private void setAllField(Dto dto, String defUsernameFld, String v) {
		 String[] a=defUsernameFld.split(",");
		 for (String fld : a) {
			 dto.put(fld, v);
		 }
		
	}

	/**
	 * 获取参数
	 * @param url
	 * @return
	 */
	public static String getParamFromURl(String url,String surl) {
		String param=null;
		if(StringUtil.isNotEmpty(url)){
			String tempUrl = url.substring(url.lastIndexOf(surl), url.length());
			String params[] = tempUrl.split("\\/");
			if(params.length==3){
			   param = params[2];
			}
			if(params.length==2){
			   param = params[1];
			}
		}
		StringUtil.xprint("param="+param);
		return param;
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		 doGet(req, resp);
	}

}
